using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
#if NET48 || NET472 || NET471 || NET47 || NET462 || NET461 || NET46 || NETCOREAPP3_1
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
#else
using System.Text.Json;
using System.Text.Json.Serialization;
#endif

namespace TangHotKey
{
    /// <summary>
    /// 热键配置管理类，负责热键配置的持久化存储
    /// </summary>
    public class HotKeyConfig
    {
        private static readonly string ConfigDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "TangHotKey");
        private static readonly string ConfigFilePath = Path.Combine(ConfigDirectory, "hotkeys.json");
        
        /// <summary>
        /// 热键配置项
        /// </summary>
        public class HotKeyItem
        {
            public HotKeyManager.ModifierKeys Modifiers { get; set; }
            public Keys Key { get; set; }
            public string Description { get; set; } = string.Empty;
            public bool IsEnabled { get; set; } = true;
            public DateTime CreatedTime { get; set; } = DateTime.Now;
            public DateTime LastUsedTime { get; set; } = DateTime.Now;
        }
        
        /// <summary>
        /// 配置数据
        /// </summary>
        public class ConfigData
        {
            public List<HotKeyItem> HotKeys { get; set; } = new List<HotKeyItem>();
            public bool AutoStartWithWindows { get; set; } = false;
            public bool ShowNotifications { get; set; } = true;
            public string Version { get; set; } = "1.0.0";
            public DateTime LastSaved { get; set; } = DateTime.Now;
        }
        
        private static ConfigData _config = new ConfigData();
        private static readonly object _lockObject = new object();
        
        /// <summary>
        /// 获取当前配置
        /// </summary>
        public static ConfigData Current => _config;
        
        /// <summary>
        /// 加载配置文件
        /// </summary>
        /// <returns>是否加载成功</returns>
        public static bool LoadConfig()
        {
            lock (_lockObject)
            {
                try
                {
                    if (!File.Exists(ConfigFilePath))
                    {
                        // 如果配置文件不存在，创建默认配置
                        _config = new ConfigData();
                        SaveConfig();
                        return true;
                    }
                    
                    var jsonString = File.ReadAllText(ConfigFilePath);
#if NET48 || NET472 || NET471 || NET47 || NET462 || NET461 || NET46 || NETCOREAPP3_1
                    var settings = new JsonSerializerSettings
                    {
                        Formatting = Formatting.Indented,
                        Converters = { new StringEnumConverter() }
                    };
                    
                    var loadedConfig = JsonConvert.DeserializeObject<ConfigData>(jsonString, settings);
#else
                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true,
                        WriteIndented = true,
                        Converters = { new JsonStringEnumConverter() }
                    };
                    
                    var loadedConfig = JsonSerializer.Deserialize<ConfigData>(jsonString, options);
#endif
                    if (loadedConfig != null)
                    {
                        _config = loadedConfig;
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    // 记录错误但不抛出异常，使用默认配置
                    System.Diagnostics.Debug.WriteLine($"加载配置文件失败: {ex.Message}");
                    _config = new ConfigData();
                }
                
                return false;
            }
        }
        
        /// <summary>
        /// 保存配置文件
        /// </summary>
        /// <returns>是否保存成功</returns>
        public static bool SaveConfig()
        {
            lock (_lockObject)
            {
                try
                {
                    // 确保配置目录存在
                    if (!Directory.Exists(ConfigDirectory))
                    {
                        Directory.CreateDirectory(ConfigDirectory);
                    }
                    
                    _config.LastSaved = DateTime.Now;
                    
#if NET48 || NET472 || NET471 || NET47 || NET462 || NET461 || NET46 || NETCOREAPP3_1
                    var settings = new JsonSerializerSettings
                    {
                        Formatting = Formatting.Indented,
                        Converters = { new StringEnumConverter() }
                    };
                    
                    var jsonString = JsonConvert.SerializeObject(_config, settings);
#else
                    var options = new JsonSerializerOptions
                    {
                        WriteIndented = true,
                        Converters = { new JsonStringEnumConverter() }
                    };
                    
                    var jsonString = JsonSerializer.Serialize(_config, options);
#endif
                    File.WriteAllText(ConfigFilePath, jsonString);
                    
                    return true;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"保存配置文件失败: {ex.Message}");
                    return false;
                }
            }
        }
        
        /// <summary>
        /// 添加热键配置
        /// </summary>
        public static void AddHotKey(HotKeyManager.ModifierKeys modifiers, Keys key, string description)
        {
            lock (_lockObject)
            {
                var hotKeyItem = new HotKeyItem
                {
                    Modifiers = modifiers,
                    Key = key,
                    Description = description,
                    IsEnabled = true,
                    CreatedTime = DateTime.Now,
                    LastUsedTime = DateTime.Now
                };
                
                _config.HotKeys.Add(hotKeyItem);
                SaveConfig();
            }
        }
        
        /// <summary>
        /// 移除热键配置
        /// </summary>
        public static bool RemoveHotKey(HotKeyManager.ModifierKeys modifiers, Keys key)
        {
            lock (_lockObject)
            {
                var item = _config.HotKeys.Find(h => h.Modifiers == modifiers && h.Key == key);
                if (item != null)
                {
                    _config.HotKeys.Remove(item);
                    SaveConfig();
                    return true;
                }
                return false;
            }
        }
        
        /// <summary>
        /// 更新热键使用时间
        /// </summary>
        public static void UpdateLastUsedTime(HotKeyManager.ModifierKeys modifiers, Keys key)
        {
            lock (_lockObject)
            {
                var item = _config.HotKeys.Find(h => h.Modifiers == modifiers && h.Key == key);
                if (item != null)
                {
                    item.LastUsedTime = DateTime.Now;
                    // 不立即保存，避免频繁IO操作
                }
            }
        }
        
        /// <summary>
        /// 清空所有热键配置
        /// </summary>
        public static void ClearAllHotKeys()
        {
            lock (_lockObject)
            {
                _config.HotKeys.Clear();
                SaveConfig();
            }
        }
        
        /// <summary>
        /// 获取配置文件路径
        /// </summary>
        public static string GetConfigFilePath() => ConfigFilePath;
        
        /// <summary>
        /// 导出配置到指定文件
        /// </summary>
        public static bool ExportConfig(string filePath)
        {
            try
            {
#if NET48 || NET472 || NET471 || NET47 || NET462 || NET461 || NET46 || NETCOREAPP3_1
                var settings = new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented,
                    Converters = { new StringEnumConverter() }
                };
                
                var jsonString = JsonConvert.SerializeObject(_config, settings);
#else
                var options = new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Converters = { new JsonStringEnumConverter() }
                };
                
                var jsonString = JsonSerializer.Serialize(_config, options);
#endif
                File.WriteAllText(filePath, jsonString);
                return true;
            }
            catch
            {
                return false;
            }
        }
        
        /// <summary>
        /// 从指定文件导入配置
        /// </summary>
        public static bool ImportConfig(string filePath)
        {
            try
            {
                if (!File.Exists(filePath)) return false;
                
                var jsonString = File.ReadAllText(filePath);
#if NET48 || NET472 || NET471 || NET47 || NET462 || NET461 || NET46 || NETCOREAPP3_1
                var settings = new JsonSerializerSettings
                {
                    Converters = { new StringEnumConverter() }
                };
                
                var importedConfig = JsonConvert.DeserializeObject<ConfigData>(jsonString, settings);
#else
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true,
                    Converters = { new JsonStringEnumConverter() }
                };
                
                var importedConfig = JsonSerializer.Deserialize<ConfigData>(jsonString, options);
#endif
                if (importedConfig != null)
                {
                    _config = importedConfig;
                    SaveConfig();
                    return true;
                }
            }
            catch
            {
                // 导入失败，保持原配置
            }
            
            return false;
        }
    }
}